package tr.edu.ozyegin.ccrg.raid.slave;

import tr.edu.ozyegin.ccrg.raid.writer.FileWriter;
import java.io.IOException;

import tr.edu.ozyegin.ccrg.raid.network.Client;
import tr.edu.ozyegin.ccrg.raid.network.ClientType;

public class Storage extends Slave{
	public Storage(String confFile){
		super(confFile);
		this.type = ClientType.Storage;
	}
	public Storage(){
		super();
		this.type = ClientType.Storage;
	}
	@Override
	public void run(){
		
	}
	@Override
	protected void doProtocol() throws InterruptedException{
		boolean flag = false;
		while(true){
			try {
				System.out.println("reading opCode");
				Short opCode = (Short)this.client.Read(Short.class);
				System.out.println("opcode "+opCode);
				switch(opCode){
				case 1:
					flag = true;
					break;
				case 2:
					this.client.Read(Short.class);
					Short port  = (Short)this.client.Read(Short.class);
					System.out.println("port "+port);
					String fileName = (String)this.client.Read(String.class);
					System.out.println("file "+fileName);
					Client tmpClient = new Client(this.conf.searchByKey("raid.master.address").getValue(),port,ClientType.Storage);
					tmpClient.Connect();
					FileWriter fw = new FileWriter(fileName,tmpClient);
					Thread th = new Thread(fw,"");
					th.start();
					th.join();
				default:
					
				}
				if(flag)break;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}